Skip to content

Add an optional local MCP server - #10472

Open
filipecavalc wants to merge 7 commits into
PathOfBuildingCommunity:devfrom
filipecavalc:feature/mcp-server
Open

filipecavalc wants to merge 7 commits into
PathOfBuildingCommunity:devfrom
filipecavalc:feature/mcp-server

Conversation

@filipecavalc

@filipecavalc filipecavalc commented Nov 16, 2026 •

Copy link
Copy Markdown

Description of the problem being solved:

Path of Building knows everything about a build, but no other program can ask it anything. Tools that want its numbers re-implement the calculations, or run it headless with their own glue code (a headless JSON-RPC proposal, #9505, went stale).

This PR adds an optional, off-by-default server inside Path of Building that speaks the Model Context Protocol (MCP), the open standard that many desktop and command-line clients use to call local tools. Once it is enabled in Options, an MCP client on the same computer can read the open build, measure changes with PoB's own calculator, make changes the way the UI does (they show live in the window and stay unsaved until the user decides), and use PoB's features: the trader, the timeless jewel finder, crafting, the Compare tab and more. Every number comes from PoB's calculations; nothing is re-implemented.

Video walkthrough (4:31)

Watch on YouTube (unlisted, 4:31)

The video shows a real session: an MCP client analysing a build, finding a helmet on the trade site, equipping it, allocating the best passive, and a tour of the other tools, then how the code fits into PoB. Every Path of Building shot was recorded by PoB itself while the client was driving it.


Turning it on

Options: one new row The dialog behind Configure...

The dialog shows the status, the port (default 49290), the token (copy / new), a Copy client configuration button (a ready mcpServers JSON for clients) and the last requests, so the user can see what a client did.

Changes happen live in the window

An item equipped by a client (items_equip, here the best helmet trade_search found):

A passive allocated by a client (tree_edit, the node tree_node_power ranked first):

A configuration option changed by a client (config_set), with the side bar following:

Excerpts of the real session shown in the video (prompts and the client's answers, built from the tools' results)

Find the best helmet for this build on the trade site, Standard league, under 10 divines.
→ trade_search (Helmet, Standard, max 10 divine)
20 listings, measured on your build: Pain Visage, Ancient Mask, 5 div: DPS +6.8%, hit pool +24.2%, chaos res to -8% · Pandemonium Veil, Jester Mask, 7 div: DPS +6.1%, hit pool +24.9% · Mind Visor, Torturer's Mask, 1 div: DPS +7.2%, hit pool +18.5%, needs 132 Dex, you have 117

Which unallocated passive adds the most damage? Allocate it.
→ tree_node_power, simulate, tree_edit
Snowforged is now allocated: RF DPS went from 86.6k to 101.6k (+17.3%). It took 10 points.

Without changing anything, use simulate to compare the next two best passives for damage, per point spent.
→ simulate × 3
Fire Damage: 1 point, +2,826 DPS. Hasty Demise: 4 points, +10,332 DPS (+10.2%). Nothing was changed.

Rank the support gems for my Righteous Fire group by damage.
→ skills_rank_supports
Concentrated Effect +38.8% · Inspiration +24.8% · Less Duration +18.8%. Every other compatible support adds nothing.

Show me how Path of Building calculates my burning damage per second.
→ calcs_breakdown
4,519.2 base × 5.75 increased × 3.01 more × 2.02 DoT multiplier × 0.643 enemy = 101,573.8 fire damage per second.


What a client can do: 33 tools, grouped by tab

Area Tool What it does
App app_status Version, what is open, unsaved changes, dialogs, Path of Exile login
Builds builds_list Saved builds and folders, with PoB's search and sort
build_open Open a saved build, a code, a build link or a new build
build_save Save, or save as a new name
build_export Build share code or XML
build_notes A build's notes (Notes tab), where guides keep their stages and advice: the open build, a saved build, a code or a build link
Side bar build_stats The side bar as shown, warnings, raw output values
build_edit Character level and notes
Calcs simulate What an item, passives or a flask would change, without changing the build
calcs_breakdown Calcs tab cells and the breakdown of a stat
Tree tree_get Class, ascendancy, points, keystones, notables, masteries, jewels, specs
tree_search PoB's tree search, with the points needed to reach each node
tree_edit Allocate or remove passives, masteries, class and ascendancy
tree_specs Passive tree sets: list, select, new, copy, rename, delete
tree_node_power The node power report for a stat
tree_timeless_jewel The timeless jewel finder
tree_tattoos Tattoos for a node: list, apply, remove
Items items_get Equipped items, item sets, other items in the build
items_equip Add an item from its text, equip, unequip, flasks
items_sets Item sets: list, select, new, copy, rename, delete
items_db_search PoB's unique and rare databases, sortable by a stat
items_craft Build an item with PoB's crafting dialogs and return its text
Trade trade_query The weighted search the trader generates for a slot or unique row (Megalomaniac, Watcher's Eye, Pearl of Tsoatha), as a link
trade_search Runs that search (or a trade link) and returns listings with prices, measured on the build, sorted as the trader's Sort By
Skills skills_get Socket groups, gems, main skill, skill sets
skills_edit Add or change gems and groups, main skill, skill sets
skills_rank_supports Support gems ranked by damage for a group
Config config_get Configuration options that differ from defaults, or a search
config_set Change options, configuration sets and custom modifiers
Compare compare_builds Builds in the Compare tab, their differences and the power report
compare_copy Copy tree, items, skills or config from a compared build
Party party Party members and their effects
Import import_character Import a character through PoB's existing Path of Exile login

Plus four prompts (analyze_build, compare_with_guide, best_upgrade, timeless_jewel) and the open build's XML as the resource pob://build/current.xml. Read-only tools are annotated as such for clients, and tools that change or replace the build are marked destructive.


How it fits

flowchart LR
    C["MCP client"] -->|"POST /mcp<br/>Bearer token"| S
    subgraph PoB["Path of Building, main thread"]
        M["main:OnFrame"] --> S["McpServer:Poll<br/>LuaSocket, 127.0.0.1"]
        S --> H["McpHttp<br/>HTTP/1.1, pure Lua"]
        H --> P["McpProtocol<br/>JSON-RPC, MCP versions,<br/>Host / Origin / token"]
        P --> T["McpTools<br/>dialog guard, unsaved state,<br/>stat changes, deferred calls"]
        T --> F["McpTools/*.lua<br/>Build, Tree, Items, Trade,<br/>Skills, Config, Calcs, Compare"]
        F --> X["PoB's own code<br/>calcsTab, spec, itemsTab, skillsTab,<br/>TradeQuery, CompareTab, ..."]
    end
Loading
sequenceDiagram
    participant C as MCP client
    participant S as McpServer (in main:OnFrame)
    participant T as McpTools
    participant B as Build / tabs
    C->>S: tools/call items_equip
    S->>T: parsed request
    T->>T: refuse if a dialog is open, check the build
    T->>B: the same functions the Items tab calls
    T->>B: modFlag + ProcessBuildFlag (recalculate)
    T-->>C: result + side bar changes (as PoB's tooltips word them)
    Note over B: drawn in the same frame, marked unsaved
Loading
  • Modules/McpHttp.lua and Modules/McpProtocol.lua: HTTP/1.1 and MCP over Streamable HTTP, pure Lua without sockets, so they are unit tested. They serve protocol version 2026-07-28 and the initialize-based 2025 versions on the same endpoint ("dual-era" server); JSON responses only, no SSE, no sessions.
  • Modules/McpServer.lua: LuaSocket (already shipped and used by LaunchServer.lua), non-blocking, polled once per frame from main:OnFrame; everything runs on the main thread between frames. SimpleGraphic skips OnFrame for an unfocused window unless a coroutine is suspended, so the server keeps one suspended while it is enabled, and waits in socket.select while nobody uses the window (a request wakes it at once).
  • Modules/McpTools.lua and Modules/McpTools/*.lua: the tool framework and the tools, one file per tab. Tools call the same functions the UI's controls call wherever possible.
  • Small behaviour-neutral refactors so the server reuses existing logic instead of copying it: main:ProcessModeChange, build:ProcessBuildFlag, build:HasUnsavedChanges, ItemsTab:GetSlotReplacementOverride, PassiveTreeView:ParseSearchString, exported helpers in CompareTab / CompareBuySimilar, and in TradeQuery: EvaluateItem, GetEvaluationSlotName, SortResults, PrepareGeneratedResults and BuildListingSearchUrl split out of the row code, optional realm/league/weights parameters, sortModes set in the constructor, and SetNotice tolerating a trader that was never opened.
  • One bug fix found on the way: SkillsTab:PasteSocketGroup(text) read the clipboard before its argument; the argument now wins (Ctrl+V passes none, so it is unchanged).
  • Documentation: docs/mcp.md (users and developers).

Safety

  • Off by default. Listens on 127.0.0.1 only. Every request needs a bearer token (stored in Settings.xml like the Path of Exile login tokens). Host and Origin are checked, so web pages cannot reach it (DNS rebinding).
  • Tools that change the build are refused while the user has a dialog open; changes mark the build unsaved, so PoB asks before closing it.
  • A build with unsaved changes is never replaced unless the client explicitly discards them (clients are told to do so only when the user agrees); Dev Mode's autosave is skipped for a discarded build (abortSave).
  • Only build_save writes build files, and it never replaces another existing file without an explicit flag.
  • Tools that use one of PoB's dialogs (timeless finder, tattoos, crafting) close it and restore what they changed (build.timelessData, remembered selections, display item).
  • Nothing is uploaded. Network access is only what PoB already does when asked: build-site downloads, character import, and trade searches through the trader's own request queue and rate limits, which only read listings.

Trying it

  1. Run Path of Building from this branch, open Options, click Configure... next to Local MCP server, tick Enable MCP server and Save.
  2. Click Copy client configuration and paste it into the MCP client's configuration:
{
  "mcpServers": {
    "path-of-building": {
      "type": "http",
      "url": "http://127.0.0.1:49290/mcp",
      "headers": { "Authorization": "Bearer <token from the dialog>" }
    }
  }
}
  1. Open a build and ask the client about it. The dialog's Recent requests list shows each call.
Without a client: one request with curl
curl -s http://127.0.0.1:49290/mcp \
  -H "Authorization: Bearer <token>" -H "Content-Type: application/json" \
  -H "Accept: application/json, text/event-stream" \
  -H "MCP-Protocol-Version: 2026-07-28" -H "Mcp-Method: tools/call" -H "Mcp-Name: app_status" \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"app_status","arguments":{},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}'

Footprint on existing code

Almost all of the diff is new files. Changes to code that already existed are small and behaviour-neutral:

Files Lines
New: server, protocol, tools Modules/Mcp*.lua, Modules/McpTools/*.lua ~10,000
New: specs spec/System/TestMcp*_spec.lua ~2,000
New: docs docs/mcp.md 130
Changed: existing PoB code Main.lua, Build.lua, ItemsTab.lua, PassiveTreeView.lua, SkillsTab.lua, CompareTab.lua, CompareBuySimilar.lua, TradeQuery.lua ~375 (added + removed)
  • No new dependencies. It uses LuaSocket (runtime/socket.dll, already used by LaunchServer.lua), dkjson and base64, all already in runtime/lua.
  • Maintenance. The specs run every tool against PoB's own objects, so a change to a tab that breaks a tool fails the test suite instead of failing silently for users.
  • Deliberately not included: uploading builds or creating share links, deleting, renaming or moving build files, and changing PoB's global Options. A client can read and export, and saving never overwrites another file.
  • Tested on: the application on Windows 11; the specs in the project's Docker test image (Linux). The GUI was not tried on macOS or Linux; the socket code is the same LuaSocket API LaunchServer.lua already relies on there.

Cost and robustness

  • Idle with the server on and a level 86 build open: under 1% of one core in the background, about 1% minimised; requests answered in ~40 ms in the background and ~140 ms minimised.
  • simulate of an item: ~45 ms. A trade search of 20 listings: ~2 s.
  • Responses use chunked transfer encoding: security software that inspects MCP traffic was seen rewriting Content-Length responses on /mcp into chunked framing without re-encoding the body, corrupting every reply; already-chunked responses pass intact.

Steps taken to verify a working solution:

  • New specs spec/System/TestMcp*_spec.lua (75 tests): HTTP parsing and framing (including malformed input); Host/Origin/token checks; both protocol eras, header validation, version errors; every tool against headless builds, checking results equal what PoB computes (e.g. simulate of an item equals equipping it), edits are visible in PoB's objects, read-only tools change nothing, failed build replacements leave the open build untouched, trade searches against recorded trade site responses, and no dialog is left open. The full suite passes (786 tests) on top of the current dev.
  • Ran the application from this branch with the server enabled and drove every tool over HTTP against a real level 86 build while the window was in the background or minimised: opening and saving builds, share codes, stats, simulate, tree edits whose reported stat changes match simulate's prediction, gem/config/item edits marked unsaved, the refusal to replace a build with unsaved changes, node power, Calcs breakdowns, support ranking, the item databases, crafting (affixes, enchants, anoints, eldritch implicits, cluster jewels), the timeless jewel finder, the trader's weighted query and live trade searches, Compare and Party, and character import through a real Path of Exile login.
  • Connected an off-the-shelf MCP client (Streamable HTTP with a bearer header, configured from the dialog's Copy client configuration) and ran the session shown in the video end to end: 11 prompts, 42 tool calls, no errors.

Link to a build that showcases this PR:

Any build; the feature is independent of build content.

Before screenshot:

N/A: before this PR there is no server and no Local MCP server row in Options.

After screenshot:

Options MCP Server dialog

A client's change shown live in the window:


Notes for reviewers. The diff is large, most of it the tool files and their specs. If you prefer, it splits cleanly into separate PRs: (1) server, protocol and read-only tools; (2) editing tools; (3) the advanced Tree tab tools; (4) Items/Trade/Compare/Party/Import. I am happy to adjust names, defaults, the Options UI or anything else to fit the project.

Path of Building can now serve the Model Context Protocol over Streamable
HTTP on 127.0.0.1, so MCP clients can read and drive the open build. It is
off by default and enabled from Options, Local MCP server.

- McpHttp and McpProtocol handle HTTP and JSON-RPC without sockets, serving
  protocol version 2026-07-28 and the initialize-based 2025 versions on the
  same endpoint, with Host, Origin and bearer token checks.
- McpServer polls non-blocking sockets from main:OnFrame and keeps frames
  running while the window is in the background, throttled when idle.
- McpTools holds the tools; this adds status, the builds list, opening,
  saving and exporting builds, side bar stats, level and notes, and simulate.
- Small refactors so the server reuses existing logic: main:ProcessModeChange,
  build:ProcessBuildFlag, build:HasUnsavedChanges,
  ItemsTab:GetSlotReplacementOverride and PassiveTreeView:ParseSearchString.
- Send HTTP/1.1 responses chunked. Security software that inspects MCP
  traffic was seen rewriting Content-Length responses on /mcp to chunked
  framing without re-encoding the body, which corrupted every reply;
  responses that are already chunked pass through intact.
- Only count cursor movement as use of the window shortly after a key or
  click in it, and wait longer between idle frames the longer the window
  stays idle (up to 1 s; a request still wakes it at once).
- Report a tool file that fails to load instead of failing startup.
Adds the remaining tools, grouped by the part of the window they use:
- Tree: tree_get, tree_search, tree_edit, tree_specs, tree_node_power,
  tree_timeless_jewel, tree_tattoos
- Items: items_get, items_equip, items_sets, items_db_search, items_craft,
  trade_query
- Skills and Config: skills_get, skills_edit, skills_rank_supports,
  config_get, config_set
- Calcs: calcs_breakdown
- Compare, Party and import: compare_builds, compare_copy, party,
  import_character
Each drives the same functions the tab's controls use and restores any
dialog or selection it borrows.

PoB changes:
- SkillsTab:PasteSocketGroup(text) now uses its argument before the
  clipboard (Ctrl+V passes none, so it is unchanged).
- CompareTab and CompareBuySimilar export the helpers the comparison report
  shares with the tab.
- build_open defers link downloads through T.Settle so failures reach the
  client instead of the download callback.

Adds docs/mcp.md and specs for every tool.
- Replacing the open build only sets abortSave right before the switch, so a
  failed build_open or import no longer closes the build on the next frame
  outside Dev Mode; build XML is validated before anything is replaced, and
  a new build's class and ascendancy before it opens.
- Deferred calls answer exactly once, never apply a result that arrives
  after their timeout, refuse to change the build while the user has a
  dialog open, and close only the dialogs they opened themselves. A tool
  that fails after changing something still marks the build unsaved and
  says so.
- Malformed chunked bodies are answered with 400 instead of raising, the
  bytes buffered per connection are capped, and unexpected errors while
  handling a request are answered with 500.
- Poll runs at the start of main:OnFrame, before input is handled, so typing
  or using a dialog counts as using the window.
- build_save refuses while a dialog is open, never runs a pending save
  action, and restores the build's name and file when writing fails.
- config_set checks the custom modifier group before changing options.
- Host and Origin must carry this server's port.
- Comparison and import callbacks detect another build opening by its tabs.
- Editing tools that remove or overwrite are marked destructive.
… build

Also offer the trader's Megalomaniac, Watcher's Eye and Pearl of Tsoatha
rows and its enchant/anoint behaviour, and split the trader's evaluation,
sorting, result preparation and listing link out of its row code so they
can be reused.
@filipecavalc
filipecavalc marked this pull request as ready for review November 16, 2026 23:42
…ild, a code or a link

Guides keep their stages and advice in the Notes tab; the compare_with_guide
prompt now reads them first.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant